<template>
  <view>
    <view style="line-height: 120rpx;color: #000000;font-size: 36rpx;width: 90%;margin: 0 auto;">
      分享海报推广
      <text style="color: #999999;font-size: 26rpx;float: right;">
        推广说明
        <text class="iconfont icon-tanhao" style="float: right;margin-left: 10rpx;"></text>
      </text>
    </view>
    <!-- @change="swiperChange" -->
    <!-- <canvas @click.stop="" :style="{ width: canvasW + 'px', height: canvasH + 'px' }"
    canvas-id='my-canvas'></canvas>-->
    <swiper :current="current" :circular="true" class="image-container" previous-margin="45rpx" next-margin="45rpx" autoplay @change="swiperChange">
      <swiper-item :class="currentIndex == index ? 'swiper-item' : 'swiper-item-side'" v-for="(item, index) in headerImg" :key="index">
        <canvas @click.stop :style="{ width: canvasW + 'px', height: canvasH + 'px' }" :canvas-id="'my-canvas'+index"></canvas>
      </swiper-item>
    </swiper>
    <!-- <carousel :img-list="imgList" url-key="url" @change="selectedBanner"/> -->
    <view class="baocun" @click="saveImage">保存海报</view>
  </view>
</template>

<script>
// import carousel from '../../components/vear-carousel.vue'
export default {
  // components: {
  // 	carousel
  // },
  data() {
    return {
      imgList: [{
        url: 'https://static-1310167831.cos.ap-nanjing.myqcloud.com/uploads/20220329/LOGO%402x.png',
        id: 1
      }, {
        url: 'https://static-1310167831.cos.ap-nanjing.myqcloud.com/uploads/20220329/LOGO%402x.png',
        id: 2
      }, {
        url: 'https://static-1310167831.cos.ap-nanjing.myqcloud.com/uploads/20220329/LOGO%402x.png',
        id: 3
      }, {
        url: 'https://static-1310167831.cos.ap-nanjing.myqcloud.com/uploads/20220329/LOGO%402x.png',
        id: 4
      },],
      type: 0,
      currentIndex: 0,
      current: 1,
      dontFirstAnimation: true,
      canvasW: 542,
      canvasH: 936,
      ctx: null,
      headerImg: [],
      qrcode: 'https://oss.zhangyubk.com/bottomab.png'
    }
  },
  onLoad() {
    this.tu()
  },
  methods: {
    tu: function () {
      let that = this
      this.post('api/client/qrcode', '', true).then(res => {
        console.log(res)
        if (res.code == 1) {
          this.qrcode = res.data.qrcode
          this.headerImg = res.data.background
          // that.__init(res.data.background[0],this.qrcode)
          for (let i = 0; i < this.headerImg.length; i++) {
            that.__init(i, this.headerImg[i], this.qrcode)
          }
        }
      })
    },

    // selectedBanner(index) {
    // 	console.log('馃', index)
    // 	this.type=index
    // },
    swiperChange(e) {
      this.dontFirstAnimation = false
      this.currentIndex = e.detail.current
      console.log(e)
      // this.$emit('change', this.currentIndex)
    },


    async __init(i, bgtu, erweima) {
      let ctx
      uni.showLoading({
        title: '',
        mask: true
      })
      ctx = uni.createCanvasContext('my-canvas' + i, this)
      this.canvasW = uni.upx2px(542);
      this.canvasH = uni.upx2px(936);


      //设置画布背景透明
      ctx.setFillStyle('rgba(255, 255, 255, 0)')
      //设置画布大小
      ctx.fillRect(0, 0, this.canvasW, this.canvasH)
      //绘制圆角背景
      this.drawRoundRect(ctx, 0, 0, this.canvasW, this.canvasH, uni.upx2px(30), '#FFFFFF')


      let headerImg = await this.getImageInfo(bgtu)
      let hW1 = uni.upx2px(542);
      let hH1 = uni.upx2px(936);
      this.drawRoundImg(ctx, headerImg.path, 0, 0, hW1, hH1, 0)
      //小程序码
      let qrcodeImg = await this.getImageInfo(erweima)
      let erweima_h = uni.upx2px(200);
      let erweima_w = uni.upx2px(200);
      let hW_ewm = uni.upx2px(200);
      let hH_ewm = uni.upx2px(200);
      ctx.drawImage(qrcodeImg.path, (this.canvasW) / 2 - erweima_w, (this.canvasH) / 2 + erweima_h,
        hW_ewm, hH_ewm)
      //延迟渲染
      setTimeout(() => {
        ctx.draw(true, () => {
          uni.hideLoading()
        })
      }, 500)
    },


    //绘制实心圆
    drawEmptyRound(ctx, x, y, radius) {
      ctx.save()
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, 2 * Math.PI, true);
      ctx.setFillStyle('rgba(0, 0, 0, .4)')
      ctx.fill();
      ctx.restore()
      ctx.closePath()
    },
    //绘制虚线
    drawDashLine(ctx, x1, y1, x2, y2, dashLength) {
      ctx.setStrokeStyle("#cccccc") //设置线条的颜色
      ctx.setLineWidth(1) //设置线条宽度
      var dashLen = dashLength,
        xpos = x2 - x1, //得到横向的宽度;
        ypos = y2 - y1, //得到纵向的高度;
        numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
      //利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
      for (var i = 0; i < numDashes; i++) {
        if (i % 2 === 0) {
          ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
          //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
        } else {
          ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
        }
      }
      ctx.stroke();
    },
    //带圆角图片
    drawRoundImg(ctx, img, x, y, width, height, radius) {
      ctx.beginPath()
      ctx.save()
      // 左上角
      ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
      ctx.stroke()
      ctx.clip()
      ctx.drawImage(img, x, y, width, height);
      ctx.restore()
      ctx.closePath()
    },
    //圆角矩形
    drawRoundRect(ctx, x, y, width, height, radius, color) {
      ctx.save();
      ctx.beginPath();
      ctx.setFillStyle(color);
      ctx.setStrokeStyle(color)
      ctx.setLineJoin('round'); //交点设置成圆角
      ctx.setLineWidth(radius);
      ctx.strokeRect(x + radius / 2, y + radius / 2, width - radius, height - radius);
      ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
      ctx.stroke();
      ctx.closePath();
    },
    //获取图片
    getImageInfo(imgSrc) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: imgSrc,
          success: (image) => {
            resolve(image);
            console.log('获取图片成功', image)
          },
          fail: (err) => {
            reject(err);
            console.log('获取图片失败', err)
          }
        });
      });
    },
    //保存图片到相册
    saveImage() {
      var that = this


      uni.getSetting({
        success: (res) => {
          //如果没有相册权限
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            //向用户发起授权请求
            uni.authorize({
              scope: "scope.writePhotosAlbum",
              success: () => {
                //授权成功保存图片到系统相册
                uni.canvasToTempFilePath({
                  canvasId: 'my-canvas' + that.currentIndex,
                  quality: 1,
                  complete: (res) => {
                    console.log('保存到相册', res);
                    uni.saveImageToPhotosAlbum({
                      filePath: res.tempFilePath,
                      success(res) {
                        uni.showToast({
                          title: '已保存到相册',
                          icon: 'success',
                          duration: 2000
                        })
                        console.log(res, 123456)
                        setTimeout(() => {
                          that.isShow = false
                        }, 2000)
                      }
                    })
                  }
                }, this);
              },
              //授权失败
              fail: () => {
                uni.hideLoading();
                uni.showModal({
                  title: "您已拒绝获取相册权限",
                  content: "是否进入权限管理，调整授权？",
                  success: (res) => {
                    if (res.confirm) {
                      //调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
                      uni.openSetting({
                        success: (res) => {
                          console.log(res.authSetting);
                        },
                      });
                    } else if (res.cancel) {
                      return uni.showToast({
                        title: "已取消！",
                      });
                    }
                  },
                });
              },
            });
          } else {
            //如果已有相册权限，直接保存图片到系统相册
            uni.canvasToTempFilePath({
              canvasId: 'my-canvas' + that.currentIndex,
              quality: 1,
              complete: (res) => {
                console.log('保存到相册', res);
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success(res) {
                    uni.showToast({
                      title: '已保存到相册',
                      icon: 'success',
                      duration: 2000
                    })
                    console.log(res, 123456)
                    setTimeout(() => {
                      that.isShow = false
                    }, 2000)
                  }
                })
              }
            }, this);
          }
        },
        fail: (res) => { },
      });
    },
    saveImage1() {
      var that = this
      uni.canvasToTempFilePath({
        canvasId: 'my-canvas',
        quality: 1,
        complete: (res) => {
          console.log('保存到相册', res);
          uni.share({
            provider: 'weixin',
            scene: 'WXSceneSession',
            type: 2,
            title: '你好呀',
            href: '../index/index',
            summary: '我是图文描述',
            imageUrl: res.tempFilePath,
            success: function (res) {
              console.log('success:' + JSON.stringify(res));
            },
            fail: function (err) {
              console.log('fail:' + JSON.stringify(err));
            }
          });
          // uni.saveImageToPhotosAlbum({
          // 	filePath: res.tempFilePath,
          // 	success(res) {
          // 		uni.showToast({
          // 			title: '已保存到相册',
          // 			icon: 'success',
          // 			duration: 2000
          // 		})
          // 		setTimeout(()=>{
          // 			that.isShow = false
          // 		},2000)
          // 	}
          // })
        }
      }, this);
    },
    // 文字换行
    drawtext(ctx, t, x, y, w) {
      //参数说明
      //ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，w：文字最大宽度
      let chr = t.split("")
      let temp = ""
      let row = []

      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < w && ctx.measureText(temp + (chr[a])).width <= w) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp)
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], x, y + (b + 1) * 16); //每行字体y坐标间隔20
      }

    },
  }
}
</script>

<style lang="scss">
page {
  background-color: #f8f8f8 !important;
  font-family: Demibold;
}
.baocun {
  width: 620rpx;
  height: 92rpx;
  background: #1fb0ac;
  border-radius: 46rpx;
  text-align: center;
  line-height: 92rpx;
  color: #ffffff;
  font-size: 28rpx;
  margin: 100rpx auto;
}

.image-container {
  width: 640rpx;
  height: 936rpx;
  margin: 0 auto;
}

.item-img {
  // width: 542rpx;
  // height: 936rpx;
  // border-radius: 14rpx;
  animation: to-big 0.3s;
  text-align: center;
}
.swiper-item-side {
  // width: 542rpx;
  // height: 936rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.swiper-item {
  width: 542rpx;
  height: 936rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.item-img-side {
  width: 542rpx;
  height: 936rpx;
  border-radius: 14rpx;
  animation: to-mini 0.3s;
}

@keyframes to-mini {
  from {
    height: 936rpx;
  }
  to {
    height: 936rpx;
  }
}
@keyframes to-big {
  from {
    height: 936rpx;
  }
  to {
    height: 936rpx;
  }
}
</style>
